package com.atguigu.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HelloController {
    @Value("${sso-server-url}")
    String ssoServerUrl;

    @ResponseBody
    @GetMapping(value = "/hello")
    public String loginPage() {
        return "hello";
    }

    @GetMapping(value = "/employees")
    public String employees(Model model, @RequestParam(value = "token", required = false) String token,
            HttpSession session) {
        if (!StringUtils.isEmpty(token)) {
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> entity = restTemplate.getForEntity("http://127.0.0.1:9988/userInfo?token=" + token,
                    String.class);
            session.setAttribute("loginUser", entity.getBody());
        }
        List<String> emps = new ArrayList<>();
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:" + ssoServerUrl + "?redirect_url=http://127.0.0.1:8081/employees";
        } else {
            emps.add("张三");
            emps.add("李四");
        }
        model.addAttribute("emps", emps);
        return "employees";
    }

}
